package com.imooc.demo.web;

import com.imooc.demo.entity.Worker;
import com.imooc.demo.service.WorkerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/worker")
public class WorkerController {
    @Autowired
    WorkerService workerService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Value("${uploadFile.worker-upload}")
    private String uploadFileWorkerUpload;

    @ResponseBody
    @RequestMapping(value = "/workerupload")
    public Map<String, Object> workerUpload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        // 封装返回小程序
        Map<String, Object> result = new HashMap<>();
        String path = null;
        //////图片访问路径
        String fileServerPath;

        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            //String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())||"JPEG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    //String realPath = request.getSession().getServletContext().getRealPath("/");
                    String realPath=uploadFileLocation+uploadFileWorkerUpload;
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;

                    //////////////////设置访问路径
                    //basePath拼接完成后，形如：http://192.168.1.20:8080/fileServer
                    /*String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                    fileServerPath = basePath + resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + trueFileName;
                    System.out.println("文件访问路径：" +   fileServerPath);*/

                    fileServerPath = resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + uploadFileWorkerUpload.substring(0, uploadFileWorkerUpload.lastIndexOf("/") + 1) + trueFileName;
                    System.out.println("文件访问路径：" + fileServerPath);


                    ////////////////////
                    // 设置存放图片文件的路径
                    path = realPath  + trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");
                }else {
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    result.put("url", null);
                    return result;
                }
            }else {
                logger.info("文件类型为空");
                result.put("url", null);
                return result;
            }
        }else {
            logger.info("没有找到相对应的文件");
            result.put("url", null);
            return result;
        }
        result.put("url",fileServerPath);
        return result;


    }


   /* @RequestMapping(value = "/insertphone",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等,此处需传入xml
    private Map<String,Object> insertPhone(@RequestParam("buyerOpenid") String buyerOpenid,
                                           @RequestParam("userPhone") String userPhone,
                                           @RequestParam("userName") String userName
    ){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPhone(userPhone);
        modelMap.put("success",userInfoService.insertPhone(userInfo));
        return modelMap;
    }*/
   //添加及修改信息
   @RequestMapping(value = "/insertworker",method = RequestMethod.POST)
   //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等,此处需传入xml
   private  Map<String,Object>  insertWorker(@RequestParam("openId") String openId,
                                             @RequestParam("name") String name,
                                             @RequestParam("phone") String phone,
                                             @RequestParam("score") BigDecimal score,
                                             @RequestParam("picture") String picture
                                             ){
       Map<String,Object>  modelMap = new HashMap<String ,Object>();
       Worker worker = new Worker();
       worker.setOpenId(openId);
       worker.setName(name);
       worker.setPhone(phone);
       BigDecimal fen = new BigDecimal("5.00");
       worker.setScore(fen);
       worker.setPicture(picture);
       Worker worker0=workerService.getWorker(worker.getOpenId());
       if(worker0!=null){
           if(worker.getName().equals(worker0.getName())==false||worker.getPhone().equals(worker0.getPhone())==false||worker.getPicture().equals(worker0.getPicture())==false) {
               worker0.setName(worker.getName());
               worker0.setPhone(worker.getPhone());
               worker0.setPicture(worker.getPicture());
               modelMap.put("success",workerService.updateWorker(worker0));
               /*worker.setScore(worker0.getScore());
               System.out.println(worker0);
               worker0.setStatus(1);
               workerService.updateWorker(worker0);
               modelMap.put("success",workerService.insertWorker(worker));*/
               modelMap.put("msg","0");
           }else {
               modelMap.put("msg","1");
           }

       }else {
           modelMap.put("msg","0");
           modelMap.put("success",workerService.insertWorker(worker));
       }
       //modelMap.put("success",workerService.insertWorker(worker));
       return modelMap;
   }

    @RequestMapping(value = "getworker",method = RequestMethod.GET)
    private  Map<String,Object>  getWorker(@RequestParam("openId") String openId){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Worker worker= workerService.getWorker(openId);
        if(worker==null){
            modelMap.put("worker","null");
        }else{
            modelMap.put("worker",worker);
        }
        return modelMap;
    }

    @RequestMapping(value = "getworkerbyid",method = RequestMethod.GET)
    private  Map<String,Object>  getWorkerById(@RequestParam("id") Integer id){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Worker worker= workerService.getWorkerById(id);
        if(worker==null){
            modelMap.put("worker","null");
        }else{
            modelMap.put("worker",worker);
        }
        return modelMap;
    }


    /*//删除
    @RequestMapping(value = "/deleteworker",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> deleteWorker(@RequestParam("openId") String openId) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
       Worker worker=workerService.getWorker(openId);
       worker.setStatus(1);
        System.out.println(worker);
        //修改信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("success",workerService.deleteWorker(worker));
        return modelMap;
    }

    //更新
    @RequestMapping(value = "/updateworker",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> updateWorker(@RequestParam("openId") String openId,
                                             @RequestParam("name") String name,
                                             @RequestParam("phone") String phone) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Worker worker = new Worker();
        worker.setOpenId(openId);
        worker.setName(name);
        worker.setPhone(phone);
        System.out.println(worker);
        //修改信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("success",workerService.updateWorker(worker));
        return modelMap;
    }*/


}
